package com.hznu.coursemanagerbackend.common.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: DragonDoor
 * @Date: 2018/12/6 14:34
 * @Description:
 */

/**
 * 参数映射到实体类转换成的map
 */
public class BeanUtils {


    public static Map<String, Object> convertBeanToMap(Object object,Map<String,Object> params) {
        Map<String, Object> map = new HashMap<>();
        try
        {
            BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors)
            {
                String key = property.getName();
                // 过滤class属性
                if (!key.equals("class"))
                {
                    map.put(key,params.get(key));
                }
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return map;
    }

    public static Map<String, Object> convertBeanToMap(Object object) {
        Map<String, Object> map = new HashMap<>();
        try
        {
            BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors)
            {
                String key = property.getName();
                // 过滤class属性
                if (!key.equals("class"))
                {
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(object);
                    if(value != null)
                    {
                        map.put(key,value);
                    }
                }
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return map;
    }

}
